/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.manager;

import com.inspur.edp.lcm.metadata.common.Utils;

public class VersionManager {
    private VersionManager() {

    }
    public static String versionCompare(String existVersion, String newVersion) {
        if (newVersion == null) {
            return existVersion;
        }

        if (existVersion == null) {
            return newVersion;
        }

        String[] existVersions = existVersion.split("\\.");
        String[] newVersions = newVersion.split("\\.");
        int first = Integer.parseInt(existVersions[0].replace(Utils.getVersionPrefix(), "")) - Integer.parseInt(newVersions[0].replace(Utils.getVersionPrefix(), ""));
        if (first > 0) {
            return existVersion;
        }
        if (first < 0) {
            return newVersion;
        }
        int second = Integer.parseInt(existVersions[1]) - Integer.parseInt(newVersions[1]);
        if (second > 0) {
            return existVersion;
        }
        if (second < 0) {
            return newVersion;
        }

        // 解决其他后缀对比问题
        String third1 = existVersions[2].replace(Utils.getVersionSuffix(), "");
        int thirdInt1;
        if (third1.contains("-")) {
            thirdInt1 = Integer.parseInt(third1.split("-")[0]);
        } else {
            thirdInt1 = Integer.parseInt(third1);
        }
        String third2 = newVersions[2].replace(Utils.getVersionSuffix(), "");
        int thirdInt2;
        if (third2.contains("-")) {
            thirdInt2 = Integer.parseInt(third2.split("-")[0]);
        } else {
            thirdInt2 = Integer.parseInt(third2);
        }
        int third = thirdInt1 - thirdInt2;

        if (third > 0) {
            return existVersion;
        }
        if (third < 0) {
            return newVersion;
        }

        if (!existVersion.endsWith(Utils.getVersionSuffix())) {
            return existVersion;
        } else {
            return newVersion;
        }
    }
}
